﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

/**
 * 创建时间：2014/12/15 13:30:07
 * 作者：yong.blackcore
 * Email：itblackhole@outlook.com
 * QQ：50404503
 */
namespace ComicIsland.Common.Converter
{
    public class ImageCacheConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                bool isRightUri = false;
                if (value != null)
                {
                    //LogHelper.LogInfo(value.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                    if (!string.IsNullOrWhiteSpace(value.ToString()))
                        isRightUri = true;
                    if (value.ToString().Trim().StartsWith("http") && Uri.IsWellFormedUriString(value.ToString().Trim(), UriKind.RelativeOrAbsolute))
                        isRightUri = true;
                    else
                        isRightUri = false;
                }
                if (isRightUri)
                {
                    Uri imageUri = new Uri(value.ToString());
                    return new StorageCachedImage(imageUri);
                    //ImageSource source = new StorageCachedImage(imageUri);
                    //return source;
                }
                else
                {
                    BitmapImage bitImage = new BitmapImage();
                    bitImage.UriSource = new Uri(KEYS.RESOURCE_ASSEMBLYNAME + "/Images/Empty404.png", UriKind.Relative);
                    return bitImage;
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.Message, this.GetType(), MethodBase.GetCurrentMethod());
                //图片异常，则使用默认的图片
                //return new Uri(Keys.RESOURCE_ASSEMBLYNAME + "/images/404.jpg", UriKind.Relative);
                BitmapImage bitImage = new BitmapImage();
                bitImage.UriSource = new Uri(KEYS.RESOURCE_ASSEMBLYNAME + "/Images/Empty404.png", UriKind.Relative);
                return bitImage;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
